<script setup lang="ts">
import { ref, provide, onMounted } from 'vue'
import { useElementHover } from '@vueuse/core'
import { dropdownSymbol } from './dropdownContext'

const props = withDefaults(defineProps<{
  triggerType?: 'click' | 'hover',
  menuPlacement?: 'center' | 'left',  // 弹出的位置：居中或者左对齐
}>(), {
  triggerType: 'hover',
  menuPlacement: 'left',
})

const emit = defineEmits<{ select: [value: string] }>()

const refDropdown = ref<HTMLDivElement>()
const visible = ref(false)
const triggerType = props.triggerType
const isClickTrigger = triggerType === 'click'
const top = ref(0)
const left = ref(0)
const toggleVisible = () => visible.value = !visible.value
const open = () => visible.value = true
const close = () => visible.value = false
const setPosition = (_top: number, _left: number) => {
  top.value = _top
  left.value = _left
}
const selected = ref('')
const select = (val: string | number) => {
  selected.value = val.toString()
  emit('select', selected.value)
}
const isHovered = isClickTrigger ? undefined : useElementHover(refDropdown, { delayLeave: 100, })

provide(dropdownSymbol, {
  isHovered,
  visible,
  triggerType,
  open,
  close,
  toggleVisible,
  top,
  left,
  setPosition,
  menuPlacement: props.menuPlacement,
  selected,
  select,
})

</script>

<template>
  <div class="kx-dropdown" ref="refDropdown">
    <slot></slot>
  </div>
</template>
